<?php

namespace App\Console\Commands;

use App\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;


class AutoSub extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:autoSub';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '测试自动分表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $tableName = 'users';
        $newTableName = $tableName . '_' .date('Ymd');
        $newTableNameKey = 'users-table-name-key';
        $oldTableName = Cache::get($newTableNameKey);
        if (!empty($oldTableName)) {
            $tableName = $oldTableName;
        }
        $userCnt = DB::table($tableName)->count();
        if ($userCnt > 100) { // 判断当前表数据量是否超额,超过后创建新表
            Schema::create($newTableName, function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
            });
            Cache::put($newTableNameKey, $newTableName);
            $this->info('处理完成');
        } else {
            $this->info('暂无更新');
        }
    }
}
